import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.AssignerWithPeriodicWatermarks;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

/**
 * @author wangzj
 * @description 模拟一个实时接收 Socket 的 DataStream 程序，
 * 代码中使用 AssignerWithPeriodicWatermarks 来设置水印，
 * 将接收到的数据进行转换，分组并且在一个 5s
 * 的窗口内获取该窗口中第二个元素最小的那条数据。
 * @date 2020/7/22 23:38
 */
public class WaterMarkDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();

        //设置为eventtime事件类型
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
        //设置水印生成时间间隔100ms
        env.getConfig().setAutoWatermarkInterval(100);

        DataStream<String> text = env
                .socketTextStream("127.0.0.1", 9000)
                //设置水印
                .assignTimestampsAndWatermarks(new AssignerWithPeriodicWatermarks<String>() {
                    //当前时间戳
                    private Long currentTimeStamp = 0L;
                    //设置允许乱序时间（）
                    private Long maxOutOfOrderness = 5000L;
                    //不处理乱序消息
//                    private Long maxOutOfOrderness = 0L;

                    @Override
                    public Watermark getCurrentWatermark() {
                        return new Watermark(currentTimeStamp - maxOutOfOrderness);
                    }

                    @Override
                    public long extractTimestamp(String element, long previousElementTimestamp) {
                        String[] str = element.split(",");
                        long timeStamp = Long.parseLong(str[1]);
                        //取最大的值作为水印时间
                        currentTimeStamp = Math.max(timeStamp, currentTimeStamp);
                        System.err.println(element + ",EventTime:" + timeStamp + ",watermark:" + (currentTimeStamp - maxOutOfOrderness));

                        return timeStamp;
                    }
                });

        text.map(new MapFunction<String, Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> map(String value) throws Exception {
                String[] str = value.split(",");
                return new Tuple2<>(str[0], Long.parseLong(str[1]));
            }
        })
                //按第一个元素进行聚合
                .keyBy(0)
                //事件窗口时间为5s
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                //取第二个元素最小的那条数据
                .minBy(1)
                .print();

        env.execute("WaterMark Test Demo");
    }
}
